package com.typing.battle.view;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.typing.battle.R;

import com.typing.battle.activity.TypingBattleChatRoomActivity;
import com.typing.battle.async.ImageAsync;
import com.typing.battle.database.FriendManager;
import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.receiver.ServerPollingReceiver;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.FriendDTO;
import com.typing.battle.value.ServerComunicationDTO;

public class FriendListViewForChatRoom extends ListView implements OnItemClickListener,OnDataSyncCompleteListener{

	private Context mContext;
	private Activity mActivity;
	private JSONObject lists;
	private JSONArray list;
	private FriendListAdapter adapter;
	private SQLiteDatabase m_db;
	private FriendManager dbMgr;
	private LinearLayout layout;
	public TextView vDescript,vName,vBlock;
	private ImageView vThumb;
	private LayoutInflater inflate;
	private PreferenceMgr mgr;
	private int rowCount = 15;
	private int currentIndex = 0;
	private int totalCount;
	
	public static final String RETURN_NAME = "friend_data";
	
	public FriendListViewForChatRoom(Context context) {
		super(context);
		mContext = context;
		mActivity = (Activity)context;
		mgr = PreferenceMgr.getInstance(context);
		inflate = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//		setBackgroundColor(Color.BLUE);
//	    getData();
		setDivider(getResources().getDrawable(R.drawable.popup_line));
		adapter =new FriendListAdapter();
		setAdapter(adapter);
		setOnItemClickListener(this);
		
	}
	public void RefreshData(){
		
		if(adapter != null){
			currentIndex = 0;
			list = new JSONArray();
			getData();
			adapter.notifyDataSetChanged();
		}
	}
	public void getNextList(){
		getData();
		adapter.notifyDataSetChanged();
	}
	private void getData(){
		/*dbMgr = new FriendManager(mContext);
		m_db = dbMgr.open();
    	// rawQuery 함수를 이용한 데이터 질의
    	return dbMgr.getFriends("SELECT * FROM "+FriendManager.DATABASE_TABLE + " ORDER BY "+FriendManager.KEY_NAME+" ASC", null);
		*/
	ServerComunicationDTO dto = new ServerComunicationDTO();
	dto.setActionType(ServerComunicationUtil.TYPE_FRIEND_SELECT);
	dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
	dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
	dto.setStartIndex(currentIndex);
	dto.setEndIndex(currentIndex + rowCount);
	try{
		ServerComunicationUtil.serverAction(dto,mContext,FriendListViewForChatRoom.this);
	}catch(Exception e){
		e.printStackTrace();
	}
}
	public class FriendListAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return list == null ? 0 : list.length();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
//			Log.d("", "getView===>>"+position);
			if(convertView ==null){
				layout  = (LinearLayout)inflate.inflate(R.layout.friend_list_row, null);
			}else{
				layout =(LinearLayout)convertView;	
			}
			
			vThumb = (ImageView)layout.findViewById(R.id.thumb_friend_name);
			vDescript = (TextView)layout.findViewById(R.id.label_friend_descript);
			vName = (TextView)layout.findViewById(R.id.label_friend_name);
			vBlock = (TextView)layout.findViewById(R.id.label_block_yn);
			try{
				JSONObject obj1 = new JSONObject(list.get(position).toString());
				//vPhoneNo.setText(obj1.get("friendPhone").toString());
				String email =obj1.get("friendEmail").toString();
				ImageAsync sync= new ImageAsync(mContext, "http://www.typoong.com/upload/"+email+"_image.jpg", vThumb);
				vDescript.setText(obj1.get("friendDescript").toString());
				vName.setText(obj1.get("friendName").toString());
				vBlock.setText("Y".equals(obj1.get("connectYn").toString()) ? "On":"Off");
				layout.setBackgroundDrawable(null);
				if(!"Y".equals(obj1.get("connectYn").toString())){
					vName.setTextColor(mContext.getResources().getColor(R.color.silver));
					vBlock.setTextColor(mContext.getResources().getColor(R.color.silver));
				}else{
					vName.setTextColor(mContext.getResources().getColor(R.color.black));
					vBlock.setTextColor(mContext.getResources().getColor(R.color.red));
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			
			return layout;
		}
		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		JSONObject obj = null;
		String email = null;
		boolean connectYn = false;
		try {
			obj = new JSONObject(list.get(position).toString());
			email = obj.get("friendEmail").toString();
			if("Y".equals(obj.get("connectYn").toString())){
				  connectYn = true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(connectYn){
			Intent intent = new Intent(mContext, TypingBattleChatRoomActivity.class);
			intent.putExtra("friendEmail", email);		
			mActivity.setResult(TypingBattleChatRoomActivity.FRIEND_WINDOW,intent);
			mActivity.finish();
		}else{
			Toast toast = Toast.makeText(mContext, "현재 접속중이 아닌 사용자입니다.",
					Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
			toast.show();
		}
	}
	public int getTotalCount(){
		return this.totalCount;
	}
	public int getCurrentIndex(){
		return this.currentIndex;
	}
	
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		String result;
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, mContext);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_FRIEND_DELETE){
				
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_FRIEND_UPDATE){
				
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_BATTLE_INVITE){
				try {
					result = (String)resultObj;
					Intent intent = new Intent(mContext,TypingBattleChatRoomActivity.class);
	        		dto = new ServerComunicationDTO();
	    			dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_JOIN);
	    			dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
	    			dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
	    			dto.setChatRoomId(result);
	    			intent.putExtra("CHAT_ROOM_ID", result);
	    			try{
	    				ServerComunicationUtil.serverAction(dto,mContext);
	    			}catch(Exception e){
	    				
	    			}
	    			mContext.startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_FRIEND_SELECT){
				try{
					
					JSONObject resultObject = new JSONObject((String)resultObj);
					JSONArray friendArray = new JSONArray(resultObject.get("friendList").toString());
					JSONArray inviteArray = new JSONArray(resultObject.get("inviteList").toString());
					//list 초기화.
					if(friendArray!=null && friendArray.length()>0)	list = new JSONArray();
					for(int i = 0 ; i < friendArray.length(); i++){
						list.put(friendArray.get(i)); 
					}
					totalCount = resultObject.getInt("totalCount");
					currentIndex = currentIndex + rowCount;
					adapter.notifyDataSetChanged();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
//		super.onSyncComplete(resultCode, dto, resultObj);
	}

	@Override
	public void onSyncComplete(int resultCode) {
		// TODO Auto-generated method stub
		
	}
}
